package user_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

// GetUserDetail 获取用户的详细信息
func GetUserDetail(c *gin.Context) {
	in := new(GetUserDetailRequest)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	user_data := new(USER)
	// err = database.DB.Model(new(models.User)).Select("username, realname, phone_number").Where("id = ?", in.ID).Find(&user_data).Error
	err = database.DB.Model(new(models.User)).Select("username").Where("id = ?", in.ID).Find(&user_data.UserName).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	depart_data := new(UserDepart)
	err = database.DB.Model(new(models.Department)).Select("department.id,department.name").Joins("left join user_depart ud on ud.depart_id=department.id").Where("ud.user_id=?", in.ID).Find(&depart_data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	role_data := new(UserRole)
	tx := database.DB.Model(new(models.Role)).Select("role.id, role.name").Joins("left join user_role ur on ur.role_id=role.id")
	err = tx.Where("ur.user_id=?", in.ID).Find(&role_data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	menu_data := new([]UserMenu)
	err = database.DB.Model(new(models.Menu)).Select("menu.id,menu.name").Joins("left join role_menu rm on rm.menu_id=menu.id").Where("rm.role_id = ?", role_data.ID).Find(&menu_data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
		"result": gin.H{
			"userinfo":   user_data,
			"departinfo": depart_data,
			"roleinfo":   role_data,
			"menuinfo":   menu_data,
		},
	})

}
